package com.nnfe.fyd.base;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.nnfe.fyd.App;
import com.nnfe.fyd.R;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.utils.LogUtil;
import com.nnfe.fyd.utils.NetworkUtil;
import com.nnfe.fyd.utils.OnClickUtil;
import com.nnfe.fyd.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/3/31.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public abstract class BaseSwipeRefreshFragment extends ActionBarFragment
        implements SwipeRefreshLayout.OnRefreshListener, Callback<HttpResult> {


    @Bind(R.id.swipe_base_content)
    SwipeRefreshLayout swipeBaseContent;
    @Bind(R.id.list_base)
    ListView listBase;
    @Bind(R.id.emptyview)
    View emptyview;


    private String TAG = "SwipeRefreshFragment";

    protected List dataList = new ArrayList();
    public int PAGE = 0;
    public int PAGE_SIZE = 10;
    public MyBaseAdapter myBaseAdapter;


    @Override
    protected void initView() {

        swipeBaseContent.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeBaseContent.setOnRefreshListener(this);

        listBase.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //Log.e(TAG, "可见第一条是:" + firstVisibleItem + "可见最后一条是: " + (firstVisibleItem + visibleItemCount) + "总数是: " + totalItemCount);
                boolean enable = false;
                LogUtil.e(TAG, "当前总条数是： " + totalItemCount);
                if (totalItemCount > 0) {
                    //  这里疯狂刷新会奔溃
                    //  java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getTop()' on a null object reference

                    enable = firstVisibleItem == 0 && listBase.getChildAt(0).getTop() == 0;
//                    if (listBase.getChildAt(0) != null) {
//                        enable = firstVisibleItem == 0 && listBase.getChildAt(0).getTop() == 0;
//                    } else {
//                        enable = firstVisibleItem == 0;
//                    }
                } else {
                    enable = true;
                }
                swipeBaseContent.setEnabled(enable);

                if (firstVisibleItem + visibleItemCount == (PAGE + 1) * PAGE_SIZE) {
                    PAGE++;
                    getListDatda();
                } else if (PAGE != 0 && totalItemCount > PAGE * PAGE_SIZE && totalItemCount < (PAGE + 1) * PAGE_SIZE) {
                    ToastUtil.showToast("没有更多了");
                }
            }
        });

        myBaseAdapter = getAdapter();
        myBaseAdapter.setData(dataList);
        listBase.setAdapter(myBaseAdapter);


        mActionBar.getMiddleContent().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (OnClickUtil.isFastDoubleClick(1500)) {
                    listBase.setSelectionAfterHeaderView();
                }
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            onRefresh();
            swipeBaseContent.setRefreshing(true);
        }
    }


    public void setDataList(List list) {
        if (list == null) {
            throw new NullPointerException("list data can not null");
        }

        if (PAGE == 0) {
            if (list.size() == 0) {
                //ToastUtil.showToast("无可用数据");
                // 空数据页面
            } else {
                dataList.clear();
                dataList.addAll(list);
            }
        } else {
            dataList.addAll(list);
        }

        // 数据为空页面
        if (dataList.size() == 0) {
            //emptyview.setVisibility(View.VISIBLE);
        } else {
            //emptyview.setVisibility(View.GONE);
        }

        myBaseAdapter.notifyDataSetChanged();
    }

    public void getListDatda() {
        getCall().enqueue(this);
    }

    @Override
    public void onResponse(Call<HttpResult> call, Response<HttpResult> response) {
        if (response.isSuccessful()) {
            onRequestFinish();
            if (response.body() == null) {
                ToastUtil.showToast("未知错误");
                return;
            }
            if (response.body() != null && response.body().getStatus() == 1) {
                ToastUtil.showToast(response.body().getMsg());
                return;
            }
            // status = 9000 token 无效
            if (response.body() != null && response.body().getStatus() == 9000) {
                ToastUtil.showToast("登录信息过期，请重新登录");
                return;
            }

            responseSuccess(call, response);
        } else {
            onRequestFinish();
            ToastUtil.showToast("服务器错误或网络异常");
            return;
        }
    }

    @Override
    public void onFailure(Call<HttpResult> call, Throwable t) {
        onRequestFinish();
        if (!NetworkUtil.isNetworkAvailable(App.getContext())) {
            ToastUtil.showToast("无网络连接，请检查网络后重试");
            return;
        }
        if (t.toString().equals("java.net.SocketTimeoutException")
                || t.toString().equals("java.net.ConnectTimeoutException")) {
            ToastUtil.showToast("请求超时，请重试");
            return;
        }
        if (t.toString().contains("ConnectException")) {
            ToastUtil.showToast("网络连接错误，请检查网络。");
            return;
        }
        if (t.toString().contains("com.google.gson.JsonSyntaxException")) {
            ToastUtil.showToast("数据解析错误");
            LogUtil.e("dada", t.toString());
            return;
        }
    }

    public abstract void responseSuccess(Call<HttpResult> call, Response<HttpResult> response);

    protected void onRequestFinish() {
        if (swipeBaseContent.isRefreshing()) {
            swipeBaseContent.setRefreshing(false);
        }
    }

    @Override
    public void onRefresh() {
        // 刷新分两步
        // 1. 先将list置顶
        // 2. 清空数据，刷新
        if (listBase.getChildCount() > 0) {
            listBase.setSelectionAfterHeaderView();
        }
        if (dataList.size() > 0) {
            dataList.clear();
        }
        PAGE = 0;
        getListDatda();
    }


    public abstract MyBaseAdapter getAdapter();

    public abstract Call<HttpResult> getCall();

    @Override
    public int getContentView() {
        return R.layout.fragment_swipe_refresh;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();
        getListDatda();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
